package main

import (
	"bufio"
	"io/ioutil"
	"os"
	"sync"
)

var (
	wg      sync.WaitGroup
	content chan []byte
)

func init() {
	content = make(chan []byte, 100)
}

func ReadFileToContent(src string, output chan []byte) error {
	defer wg.Done()
	srcFileObj, err := os.Open(src)
	if err != nil {
		return err
	}

	srcContent, err := ioutil.ReadAll(srcFileObj)
	if err != nil {
		return err
	}

	output <- srcContent

	return nil
}

func CombineToFile(input chan []byte, dest string) error {
	defer wg.Done()

	destFileObj, err := os.OpenFile(dest, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0755)
	if err != nil {
		return err
	}
	defer destFileObj.Close()

	destBuffer := bufio.NewWriter(destFileObj)

	for text := range input {
		_, err := destBuffer.Write(text)
		if err != nil {
			return err
		}
		destBuffer.WriteByte('\n')
		destBuffer.Flush()
	}
	return nil
}

func main() {

	wg.Add(3)
	go ReadFileToContent("./example1", content)
	go ReadFileToContent("./example2", content)
	go ReadFileToContent("./example3", content)

	wg.Wait()
	close(content)

	wg.Add(1)
	go CombineToFile(content, "./exampleCombine")

	wg.Wait()
}
